package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.domain.entity.Employee;
import com.ruoyi.system.domain.entity.EmployeeServiceRecord;
import com.ruoyi.system.domain.entity.ServiceRecord;
import com.ruoyi.system.mapper.EmployeeMapper;
import com.ruoyi.system.mapper.EmployeeServiceRecordMapper;
import com.ruoyi.system.mapper.ServiceRecordMapper;
import com.ruoyi.system.service.IServiceRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServiceRecordServiceImpl extends ServiceImpl<ServiceRecordMapper, ServiceRecord> implements IServiceRecordService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private EmployeeServiceRecordMapper employeeServiceRecordMapper;

    @Override
    public ServiceRecord getWithEmployees(Long id) {
        ServiceRecord serviceRecord = this.getById(id);
        if (serviceRecord != null) {
            List<Employee> employees = employeeMapper.selectByServiceRecordId(id);
            serviceRecord.setEmployees(employees);
        }
        return serviceRecord;
    }

    @Override
    @Transactional
    public boolean saveWithEmployees(ServiceRecord serviceRecord, List<Long> employeeIds) {
        // 保存服务记录
        boolean saved = this.save(serviceRecord);
        if (saved && employeeIds != null && !employeeIds.isEmpty()) {
            // 保存关联关系
            List<EmployeeServiceRecord> relations = employeeIds.stream()
                    .map(employeeId -> {
                        EmployeeServiceRecord esr = new EmployeeServiceRecord();
                        esr.setEmployeeId(employeeId);
                        esr.setServiceRecordId(serviceRecord.getId());
                        return esr;
                    })
                    .collect(Collectors.toList());

            // 批量保存关联关系
            for (EmployeeServiceRecord relation : relations) {
                employeeServiceRecordMapper.insert(relation);
            }
        }
        return saved;
    }
}